<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link href="bootstrap-3.3.7-dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link type="text/css" href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        .main {
            margin: 10px 5px 5px 5px;
            overflow: hidden;
        }

        .autoPrint {
            box-sizing: border-box;
            margin: 10px 5px;
        }

        .autoPrint button {

        }

        .search {
            box-sizing: border-box;
            margin: 10px 5px;
        }

        .search input {
            margin-right: 5px;
        }

        .search button {
            width: 80px;
            height: 28px;
        }

        #line table {
            text-align: center;
        }

        #history table {
            text-align: center;
        }

        table thead th {
            text-align: center;
        }

        .last {
            width: 12px;
            background-color: #F0F0F0;
            border: none;
        }

        .table1 thead, tbody tr {
            display: table;
            width: 100%;
            table-layout: fixed;
        }

        .table1 tbody {
            display: block;
            height: 460px;
            overflow-y: scroll;
        }

        .table1 {
            margin-top: 10px;
        }

        .table2 thead, tbody tr {
            display: table;
            width: 100%;
            table-layout: fixed;
        }

        .table2 tbody {
            display: block;
            height: 460px;
            overflow-y: scroll;
        }

        .table2 {
            margin-top: 10px;
        }

        .tab-pane {
            background-color: white;
            min-height: 520px !important;
            max-height: 520px !important;
            margin-top: 2px;
        }

        .showAuto {
            display: none;
        }

        .showClose {
            display: inline-block;
        }

        #pop {
            display: none;
            color: #ffff66;
            font-weight: bolder;
            text-align: center;
            line-height: 40px;
            position: fixed;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom: 0px;
            margin: auto;
            background-color: #99cc66;
            width: 180px;
            height: 40px;
            border-radius: 50px;
            z-index: 100;
        }

        #disconnect {
            display: none;
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 9999;
            background-color: rgba(0, 0, 0, .5);

        }

        #disconnect h3 {
            position: absolute;
            width: 300px;
            height: 150px;
            line-height: 150px;
            color: red;
            background-color: #f5f5f5;
            border-radius: 10px;
            text-align: center;
            left: 0;
            right: 0;
            bottom: 0;
            top: 0;
            margin: auto;
        }
    </style>

</head>
<body>
<div id="disconnect">
    <h3>网络异常 ......</h3>
</div>
<!--气泡显示打印成功-->
<div id="pop"></div>

<div class="all">
    <div class="main">
        <div class="row">
            <div class="col-md-12">
                <!-- Nav tabs -->
                <ul class="nav nav-tabs" role="tablist">
                    <li role="presentation" class="active"><a href="#line" aria-controls="line" role="tab"
                                                              data-toggle="tab">队列打印信息</a></li>
                    <li role="presentation"><a href="#history" aria-controls="history" role="tab" data-toggle="tab">历史打印记录</a>
                    </li>
                </ul>
                <!-- Tab panes -->
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="line">
                        <div class="table1">
                            <div class="autoPrint">
                                <button class="showAuto btn btn-info btn-sm">开启自动打印</button>
                                <button class="showClose btn btn-info btn-sm">关闭自动打印</button>
                            </div>
                            <table class="table table-hover table-bordered theadstyle">
                                <thead>
                                <tr class="info">
                                    <!--<th>序号</th>-->
                                    <th class="td1">排队号</th>
                                    <th class="td2">患者姓名</th>
                                    <th class="td3">患者性别</th>
                                    <th class="td4">患者年龄</th>
                                    <th class="td5">科室名</th>
                                    <th class="td6">检查室名</th>
                                    <!--<th class="td7">前方等待人数</th>-->
                                    <th class="td8">打印状态</th>
                                    <th class="td9">操作</th>
                                    <th class="last"></th>
                                </tr>
                                </thead>

                                <tbody id="waitingContent">

                                </tbody>

                            </table>
                        </div>
                    </div>

                    <div role="tabpanel" class="tab-pane" id="history">
                        <div class="table2">
                            <table class="table table-hover table-bordered" id="already">
                                <thead>
                                <tr class="info">
                                    <!--<th>序号</th>-->
                                    <th class="td1">排队号</th>
                                    <th class="td2">患者姓名</th>
                                    <th class="td3">患者性别</th>
                                    <th class="td4">患者年龄</th>
                                    <th class="td5">科室名</th>
                                    <th class="td6">检查室名</th>
                                    <th class="td7">打印状态</th>
                                    <th class="td8">操作</th>
                                    <th class="last"></th>
                                </tr>
                                </thead>
                                <tbody id="alreadyContent">

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="bootstrap-3.3.7-dist/js/jquery-1.9.1.min.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="../js/sockjs.js"></script>
<script src="../js/stomp.js"></script>

<script>
    //定时打印定时器
    var autoTimer;
    // 自动打印标志 默认开启
    var autoFlag = true;
    // 未打印队列
    var notPrintList = [];
    // 已打印队列
    var okPrintList = [];
    // 配置文件信息
    var g_properties;

    /**
     * 捕获异常
     */
//    window.onerror = function () {
//        alert(arguments[0]);
//        // 阻止在控制台中打印错误信息
//        return true;
//    };

    //初始加载
    $(function () {
        // 点击开启自动打印按钮  隐藏关闭自动打印按钮
        $('.showAuto').click(function () {
            $('.showAuto').css('display', 'none');
            $('.showClose').css('display', 'inline-block');
            $(".lasttdone").attr({"disabled": "disabled"});
            autoFlag = true;
            AutoPrint();
        });

        // 点击关闭自动打印按钮  隐藏开启自动打印按钮
        $('.showClose').click(function () {
            autoFlag = false;
            // 清除定时器
            window.clearInterval(autoTimer);
            autoTimer = '';

            $('.showAuto').css('display', 'inline-block');
            $('.showClose').css('display', 'none');
            $('.lasttdone').removeAttr("disabled");
        });

        //定时执行，3秒后执行
        var t1 = window.setTimeout(refreshCount, 1000 * 3);

        function refreshCount() {
            // 获取配置文件信息
            getClientProperties();
            //去掉定时器
            window.clearTimeout(t1);
        }
    });

    // 开启自动打印定时器
    function AutoPrint() {
        autoTimer = setInterval(function () {
            console.log("定时---自动打印");
            if (notPrintList != null && notPrintList.length > 0 && autoFlag) {
                var i = 0;
                // var print = app.print(JSON.stringify(notPrintList[i]));
                console.log("自动打印");
                console.log(JSON.stringify(notPrintList[i]));

                var print = 'ok';
                if (print == 'ok') {
                    console.log("自动打印=====打印完成");
                    console.log(notPrintList[i]);
                    // 发送打印完请求
                    endPrint(notPrintList[i].departmentId, notPrintList[i].checkId, notPrintList[i].queueId, notPrintList[i].inspectId);
                    // 加载到已完成队列列表
                    prependToEnd(notPrintList[i]);
                    // 添加到已完成队列
                    okPrintList.push(notPrintList[i]);
                    // 页面删除当前行
                    $("#show-" + notPrintList[i].queueId).remove();
                    // 打印完成气泡
                    pop(notPrintList[i].queueId);
                    //从列表删除当前数据
                    notPrintList.splice(i, 1);
                } else {
                    alert('打印失败！');
                }
            }
            else {
                console.log("打印完成， 清除定时器");
                // 没有需要打印的信息，清除定时器
                window.clearInterval(autoTimer);
                autoTimer = '';
            }
        }, 5000)
    }

    // 获取客户端配置信息
    function getClientProperties() {
        // var properties = app.getClientProperties();
        var properties = '{"clientType":"2","clientId":"86e28557-dbe7-46b4-bf5c-174c4b038a00","clientName":"放射科打印端","deptId":"放射科","checkRoomId":"DR一室"}';
        var _properties = eval("(" + properties + ")");
        g_properties = _properties;

        //初始获取队列信息 发送ajax请求 将缓存队列信息存入alldata
        getDataFromServer(_properties.deptId, _properties.checkRoomId);

        //初始建立websocket连接并展示数据
        onlyConn(_properties.deptId);
    }

    //初始获取队列信息 发送ajax请求 将缓存队列信息存入alldata
    function getDataFromServer(deptId, checkRoomId) {
        var checkRooms = checkRoomId.split(",");
        for (var i = 0; i < checkRooms.length; i++) {
            $.ajax({
                url: "/queue/cacheCheckRoom?deptId=" + deptId + "&checkRoomId=" + checkRooms[i],
                type: "GET",
                dataType: "json",
                success: function (res) {
                    var result = res.data;
                    for (var i = 0; i < result.length; i++) {
                        // 未打印
                        if (result[i].printStatus != 1) {
                            // 追加并保存到未打印队列
                            appendToNot(result[i]);
                            notPrintList.push(result[i]);
                        } else {
                            // 添加并保存到已打印队列
                            prependToEnd(result[i]);
                            okPrintList.push(result[i]);
                        }
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        }
        // 开始自动打印
        AutoPrint();
    }

    // 追加到未打印页面
    function appendToNot(data) {
        var str1 = "<tr style='background-color: white' userId=show-" + data.queueId + ">"
            + "<td class='td1' >" + data.queueId + "</td>"
            + "<td class='td2'  >" + data.patientName + "</td>"
            + "<td class='td3' >" + data.patientSex + "</td>"
            + "<td class='td4' >" + data.patientAge + "</td>"
            + "<td class='td5' >" + data.department + "</td>"
            + "<td class='td6' >" + data.checkRoom + "</td>"
            + "<td class='td8'>未打印</td>"
            + "<td class='lasttd' >"
            + "<input userType='button' "
            + "class='btn btn-info lasttdone' value='打印' "
            + "style='margin: -2px auto;width: 80px;height: 28px;padding: 0px' "
            + "onclick=handPrintOne('" + data.queueId + "') ></td>"
            + "</tr>";
        // 追加到未打印页面
        $("#waitingContent").append(str1);
    }

    // 添加到已经完成队列
    function prependToEnd(data) {
        var str = "<tr  style='background-color: white'>"
            + "<td class='td1' >" + data.queueId + "</td>"
            + "<td class='td2' >" + data.patientName + "</td>"
            + "<td class='td3' >" + data.patientSex + "</td>"
            + "<td class='td4' >" + data.patientAge + "</td>"
            + "<td class='td5' >" + data.department + "</td>"
            + "<td class='td6' >" + data.checkRoom + "</td>"
            + "<td class='td8' >已打印</td>"
            + "<td class='lasttd' >"
            + "<input userType='button'  value='重新打印' class='btn btn-info' "
            + "style='margin: -2px auto;width: 80px;height: 28px;padding: 0px'"
            + "onclick=handPrintTwo(" + data.queueId + ") ></td>"
            + "</tr>";
        // 追加到已打印队列
        $("#alreadyContent").prepend(str);
    }

    function data() {
        jeDate({
                dateCell: "#start",
                format: "YYYY-MM-DD hh:mm:ss",
                isTime: true
            }
        );
        jeDate({
                dateCell: "#end",
                format: "YYYY-MM-DD hh:mm:ss",
                isTime: true
            }
        );
    }

    //初次连接后台 并展示数据
    function onlyConn(deptId) {
        //重连timer
        var timer1;
        // 建立连接对象
        var socket = new SockJS('/zd-queuing-websocket');
        // 获取STOMP子协议的客户端对象
        var stompClient = Stomp.over(socket);
        // 向服务器发起websocket连接
        stompClient.connect({},
            function (frame) {
                $("#disconnect").hide();
                if (timer1) {
                    clearInterval(timer1)
                }
                // 订阅服务端提供的新增患者消息
                stompClient.subscribe('/newPatient/dept/' + deptId, function (msg) {
                    var result = JSON.parse(msg.body);
                    console.log("新患者");
                    console.log(result);
                    var checkRoomIds = g_properties.checkRoomId.split(",");
                    for (var i = 0; i < result.length; i++) {
                        // 查询科室ID是否是所属科室
                        for (var k = 0; k < checkRoomIds.length; k++) {
                            if (checkRoomIds[k] == result[i].checkId) {
                                // 是所属科室的
                                for (var j = 0; j < result[i].queueDtoList.length; j++) {
                                    var nowData = result[i].queueDtoList[j];
                                    console.log(nowData)
                                    // 开启了自动打印
                                    if (autoFlag) {
                                        // 定时器存在
                                        if (autoTimer) {
                                            // 添加到未打印队列
                                            notPrintList.push(nowData);
                                            // 追加到页面
                                            appendToNot(nowData);
                                        }
                                        // 定时器不存在
                                        else {
                                            // var print = app.print(JSON.stringify(nowData));
                                            console.log("新患者====自动打印");
                                            console.log(JSON.stringify(nowData));
                                            var print = 'ok';
                                            if (print == 'ok') {
                                                console.log("新患者====打印成功");
                                                // 发送打印完请求
                                                endPrint(nowData.departmentId, nowData.checkId, nowData.queueId, nowData.inspectId);
                                                //添加到已完成队列
                                                prependToEnd(nowData);
                                                okPrintList.push(nowData);
                                            } else {
                                                // 添加到未打印队列
                                                notPrintList.push(result[i].queueDtoList[j]);
                                                // 追加到页面
                                                appendToNot(result[i].queueDtoList[j]);
                                            }
                                        }
                                    }
                                    // 未开启自动打印
                                    else {
                                        // 添加到未打印队列
                                        notPrintList.push(result[i].queueDtoList[j]);
                                        // 追加到页面
                                        appendToNot(result[i].queueDtoList[j]);
                                    }
                                }
                            }
                        }
                    }
                });
                stompClient.subscribe('/zd-call/cleanCache', function () {
                    alert("定时清除数据")
                    clearInterval(autoTimer);
                    clearInterval(timer1);
                    okPrintList = [];
                    notPrintList = [];
                    $("#waitingContent").html("");
                    $("#alreadyContent").html("");
                })
            },
            function errorCallBack(error) {
                // 显示网络异常
                $("#disconnect").show();
                // 清除数据
                okPrintList = [];
                notPrintList = [];
                $("#waitingContent").html('');
                // 连接发生错误时的处理函数
                timer1 = setInterval(function () {
                    window.location.reload()
                }, 2000)
            });
    }

    //未打印界面  打印方法
    function handPrintOne(nowQueueId) {
        // var print;
        for (var index in notPrintList) {
            if (notPrintList[index].queueId === nowQueueId) {
                // print = app.print(JSON.stringify(alldata[index]));
                console.log("未打印====打印");
                console.log(JSON.stringify(notPrintList[index]));
            }
        }
        var print = 'ok';
        if (print == 'ok') {
            // 找到当前患者信息
            for (var index in notPrintList) {
                if (notPrintList[index].queueId === nowQueueId) {
                    console.log("打印完成");
                    console.log(notPrintList[index]);
                    // 打印完成气泡
                    pop(nowQueueId);
                    // 发送打印完请求
                    endPrint(notPrintList[index].departmentId, notPrintList[index].checkId, notPrintList[index].queueId, notPrintList[index].inspectId);
                    // 添加到已完成队列
                    prependToEnd(notPrintList[index]);
                    okPrintList.push(notPrintList[index]);
                    // 从未打印队列中删除
                    notPrintList.splice(index, 1);
                }
            }
            // 删除当前行
            $("#show-" + nowQueueId).remove();
        } else {
            console.log('未打印====打印失败！');
        }
    }

    //已完成队列  打印方法
    function handPrintTwo(nowQueueId) {
        console.log("重新打印");
        // var print;
        for (var index in okPrintList) {
            if (okPrintList[index].queueId == nowQueueId) {
                // print = app.print(JSON.stringify(alldata[index]));
                console.log("已打印====打印");
                console.log(JSON.stringify(okPrintList[index]));
            }
        }
        var print = 'ok';
        if (print == 'ok') {
            //提示打印成功气泡
            pop(nowQueueId);
        } else {
            console.log('已打印====打印失败！');
        }
    }

    //新加的气泡代码
    function pop(data) {
        document.getElementById('pop').innerHTML = data + '打印成功！';
        document.getElementById('pop').style.display = "block";
        var t1 = setTimeout(function () {
            document.getElementById('pop').style.display = "none";

            window.clearTimeout(t1);
        }, 2500);
    }

    // 打印完成发送请求
    function endPrint(deptId, checkRoomId, queueId, inspectId) {
        $.ajax({
            url: "/zd-server/printFinish",
            type: "post",
            dataType: "json",
            data: {
                deptId: deptId,
                checkRoomId: checkRoomId,
                queueId: queueId,
                inspectId: inspectId
            },
            success: function (data) {

            },
            error: function (data) {
                alert("修改打印信息失败");
            }
        });
    }

</script>
</body>
</html>